#pragma once

#include <sys/epoll.h>
#include <cstring>
#include "nocopy.hpp"
#include "log.hpp"


class Epoller : public nocopy
{
    static const int size = 128;
public:
    Epoller()
    {
        _epfd = epoll_create(size);
        if(_epfd == -1)
        {
            lg(Warning, "epoll create fail!, strerr: %s", strerror(errno));
        }
        else
        {
            lg(Info, "epoll create success! _epfd: %d", _epfd);
        }
    }

    int EpollerWait(struct epoll_event* revs, int num, int timeout = -1)
    {
        //                                    timeout  非阻塞  一直阻塞
        int n = epoll_wait(_epfd, revs, num, timeout);
        return n;
    }

    void EpollerUpdate(int oper, int sockfd, uint32_t event)
    {
        int n;
        if(oper == EPOLL_CTL_DEL)
        {
            n = epoll_ctl(_epfd, oper, sockfd, nullptr);
            if(n < 0)
                lg(Error, "epoll event delete fail!");
            lg(Debug, "epoll delete fd : %d", sockfd);
        }
        else
        {
            struct epoll_event ev;
            ev.events = event;
            ev.data.fd = sockfd;

            n = epoll_ctl(_epfd, oper, sockfd, &ev);
            if(n < 0)
                lg(Error, "epollctl fail!");
        }
    }

    ~Epoller()
    {
        if(_epfd > 0)
            close(_epfd);
    }
private:
    int _epfd;
};